<?php  
/* OpenBIBLIO -- A library administration web interface
 * Copyright (C) 2011-2012 Laurent Luyssen   <big.lol13@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

session_start();
include_once "../../includes/db.inc";
include_once "../../includes/functions.inc";
include_once "lusDAO.php";
include_once "../../includes/session.inc";
include_once "../../includes/colCfgDAO.inc";
include_once "../../includes/resultPagination.inc";
require_once "../../includes/searchParams.inc";
include_once "../../includes/header.inc";

?>

<script type="text/javascript">
function submitform(form_name, column) {
	if (column != '') 
		document.forms[form_name].sort_col.value = column;
	document.forms[form_name].submit();
}

function newPopup(url) {
	popupWindow = window.open(url,'popUpWindow',
'height=700,width=800,left=10,top=10,resizable=yes,scrollbars=yes,toolbar=no,menubar=no,location=no,directories=no,status=no');
}

function updateStatus(livre_id, eleve_id, value) {	
	xmlhttp=new XMLHttpRequest();
	xmlhttp.open("GET" ,"contrib/lus/modreaders.php?livre_id=" + livre_id + "&eleve_id=" + eleve_id + "&lu=" + value, false);
	xmlhttp.send();
}
</script>


<?php
	// search criteria	
	$dao = LusDAO::getInstance();
	$cur_page = 0;
	if ($_SERVER['REQUEST_METHOD'] == 'POST')
		processPostData($dao);
	else {
		if (isset($_GET['page']) && !empty($_GET['page'])) 
			$cur_page = $_GET['page'];
	}	
	displaySearchParams($dao);
	

    $rec_bypage = get_max_record();
    $dao->setRowsPerPage($rec_bypage);
    $dao->setStartRow($cur_page * $rec_bypage);
    if (!$dao->doSearch())
		print "PROBLEME : ".biblio_db_error()."<br>".$dao->getQuery(); 
	else {
		/*
		 * # of results found
		 */
		$total_rows = $dao->getFoundRowCount();
		echo "<CENTER>";                
		echo _("Nombre d'enregistrement(s) trouv&eacute;(s) : ").$total_rows;
		echo "<br/><br/>\n";
		
		/*
		 *  Table header
		 */
		$allowedCols = SearchDAO::getAllowedCols();
		if (isset($_SESSION['login']))
			$login = $_SESSION['login'];
		else
			$login = "";
		$col_cfg = new ColCfgDAO($login, "read");
		$cols = $col_cfg->getConfig();
		$sort_col   = $dao->getPrimarySortColumn();
		$sort_order = $dao->getPrimarySortOrder();

        if ($sort_order == DBSortOrder::desc)
			$img = '<img src="images/arrow_down.gif"/>';
        else
			$img = '<img src="images/arrow_up.gif"/>';
				
		echo "<TABLE class=\"search_results\">\n<TR>";
		foreach ($cols as $col) {
			if (!SearchDAO::isAllowedCol($col->db_name))
				continue;
			echo '<th><a href="javascript:submitform(\'search_form\', \''.$col->db_name.'\')">';
			echo $allowedCols[$col->db_name];
			if ($sort_col == $col->db_name)
				echo $img;
			echo '</a></th>';
		}
		// List of readers
		if (!empty($login)) {
			$sql = "SELECT e.id, e.prenom, e.nom FROM eleves e JOIN classes c ON e.classe_id = c.id WHERE c.classe = 'lecteurs'";
			$result = biblio_db_query($sql);
			if (!$result) 
				die("PROBLEME : " .biblio_db_error());
			$readers = array();
			while (($row = biblio_db_fetch_array($result))) {
				$readers[$row['id']] = array ('name' => $row['nom'], 'firstname' => $row['prenom']);
			}
			foreach ($readers as $id => $reader) 
				echo "<th>".$reader['firstname']."</th>";
		}
		echo "</tr>";
        
		/*
		 * Results
		 */
		$i=0;
		while ($row = $dao->getRow()) {      
            $i++;
            $liv_id = $row['id'];                                            	
            // Check if book is already borrowed            
			if (isset($row['emprunteur'])) {
				$style = "borrowed";
			}
			else {
				if ($i%2 == 1)
					$style = "odd";
				else 
					$style = "even";
			}						
            echo "\n<tr class=\"$style\">";
			
			foreach ($cols as $col) {
				if (!SearchDAO::isAllowedCol($col->db_name))
					continue;
				$link = "JavaScript:newPopup('resume.php?id=".$liv_id."');";
				echo '<td><a href="'.$link.'">'.$row[$col->db_name].'</a></td>';
			}
			
            if (!empty($login)) {
				foreach($readers as $id => $reader)  {
					echo '<td align="center">';
					if (isset($row['readers']) && isset($row['readers'][$id]))
						$checked = 'checked = "checked"';
					else 
						$checked = '';
					$js = 'onclick="javascript:updateStatus(';
					$js .= "'$liv_id',";
					$js .= "'$id',";
					$js .= 'this.checked);"';
					echo '<input type="checkbox" '.$checked.' '.$js.'"></input>';
					echo '</td>';
				}
			}
			echo "</tr>\n";
		}
		echo "</TABLE><br>";
		
 		/*
		 * Pagination
		 */
		if (($rec_bypage > 0) && ($total_rows > $rec_bypage) ) {
			$last_page = ceil($total_rows / $rec_bypage);
			$pagination = new ResultPagination('contrib/lus/index.php?page=$PAGE', $cur_page, $last_page);
			echo $pagination->toHtml();
		}
		echo "</CENTER>";
	} 
	$dao->saveToSession();

?>
<br/><br/>
<div>
	<span id=left-text>
		<A HREF="index.php"><?php echo _("retour menu principal"); ?></A>
	</span>
</div>

<?php 
include("../../includes/footer.inc");
?>
